<template>
    <div class="stock-transfer-page">
        <!-- 顶部信息栏 -->
        <div class="top-bar">
            <el-form :model="form" inline label-width="80px">
                <el-form-item label="单据日期">
                    <el-date-picker v-model="form.billDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
                </el-form-item>
                <el-form-item label="业务员">
                    <el-select v-model="form.salesman" placeholder="选择业务员" @change="handleSalesmanChange"
                        style="width: 200px;">
                        <el-option v-for="item in salesmanOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="btn-group">
                <el-button type="primary" @click="handleSaveAndNew">保存并新增</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
                <el-button @click="handleBatchImport">批量导入</el-button>
                <el-button type="success" @click="handleApprove">审核</el-button>
                <el-button @click="handleUploadAttachment">上传附件</el-button>
                <span class="bill-no">单据编号: {{ form.billNo }}</span>
            </div>
        </div>

        <!-- 商品录入表格（带每行增删按钮） -->
        <el-table :data="tableData" border style="width: 100%; margin-top: 16px"
            :header-cell-style="{ background: '#F8F9FA' }">
            <!-- 操作列（添加/删除行） -->
            <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                    <el-button type="primary" size="mini" icon="el-icon-plus"
                        style="background: #67C23A; border-color: #67C23A; margin-right: 4px"
                        @click="handleAddRow(scope.$index)">添加</el-button>

                    <el-button v-if="scope.$index !== 0" type="danger" size="mini" icon="el-icon-minus"
                        style="background: #F56C6C; border-color: #F56C6C"
                        @click="handleDeleteRow(scope.$index)">减少</el-button>
                </template>
            </el-table-column>

            <!-- 商品录入列 -->
            <el-table-column label="商品-扫描枪录入" width="280">
                <template #default="scope">
                    <el-input v-model="scope.row.goodsInput" placeholder="输入商品或扫码" clearable style="width: 200px;" />
                    <el-button type="text" @click="openGoodsSelectDialog(scope.row, scope.$index)">选择</el-button>
                </template>
            </el-table-column>

            <!-- 其他商品信息列 -->
            <el-table-column prop="goodsCategory" label="商品类别" width="120" />
            <el-table-column prop="goodsRemark" label="商品备注" width="120" />
            <el-table-column prop="attributeCode" label="属性条码" width="120" />
            <el-table-column prop="brand" label="品牌" width="100" />
            <el-table-column prop="attribute" label="属性" width="100" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="quantity" label="数量" width="80">
                <template #default="scope">
                    <el-input v-model.number="scope.row.quantity" placeholder="输入数量" clearable />
                </template>
            </el-table-column>
            <el-table-column prop="batch" label="批量" width="80" />
            <el-table-column prop="wholePackage" label="整件数包" width="100" />
            <el-table-column prop="outWarehouse" label="调出仓库" width="120">
                <template #default="scope">
                    <el-select v-model="scope.row.outWarehouse" placeholder="选择仓库">
                        <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="inWarehouse" label="调入仓库" width="120">
                <template #default="scope">
                    <el-select v-model="scope.row.inWarehouse" placeholder="选择仓库">
                        <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="availableStock" label="可用库存(调出仓)" width="140" />
            <el-table-column prop="relatedOrderNo" label="关联调拨订单号" width="160" />
            <el-table-column prop="remark" label="备注" width="120" />
        </el-table>

        <!-- 合计及备注栏 -->
        <div class="summary-bar" style="margin-top: 8px">
            <el-input type="textarea" v-model="form.remark" placeholder="暂无备注信息" rows="2" style="width: 100%" />
        </div>

        <!-- 底部操作栏 -->
        <div class="bottom-bar" style="margin-top: 16px">
            <el-button @click="handleHistoryBills">历史单据</el-button>
        </div>

        <!-- 商品选择弹窗 -->
        <el-dialog title="选择商品" v-model="goodsSelectDialogVisible" width="800px" @close="handleGoodsSelectDialogClose">
            <!-- 顶部搜索及分类 -->
            <div class="goods-dialog-header">
                <el-input v-model="goodsSearchKey" placeholder="输入商品编号/名称/型号/品牌" clearable
                    style="width: 240px; margin-right: 12px" @keyup.enter="searchGoods" />
                <el-select v-model="warehouseFilter" placeholder="仓库">
                    <el-option label="全仓库" value=""></el-option>
                    <el-option label="主仓库" value="main"></el-option>
                </el-select>
                <el-checkbox v-model="showZeroStock">零库存商品</el-checkbox>
                <el-button type="primary" @click="searchGoods">查询</el-button>
                <el-button @click="resetGoodsSearch">重置</el-button>
            </div>

            <!-- 分类树 + 商品列表布局 -->
            <div class="goods-dialog-body">
                <div class="category-tree" style="width: 200px; margin-right: 12px">
                    <el-tree :data="categoryTree" :props="treeProps" default-expand-all show-checkbox
                        @check="handleCategoryCheck" />
                </div>
                <div class="goods-list" style="flex: 1; height: 300px; overflow-y: auto;">
                    <el-table :data="goodsList" border style="width: 100%" @selection-change="handleGoodsSelection">
                        <el-table-column type="selection" width="50" />
                        <el-table-column prop="goodsCode" label="商品编号" width="120" />
                        <el-table-column prop="goodsName" label="商品名称" width="200" />
                        <el-table-column prop="spec" label="规格型号" width="120" />
                        <el-table-column prop="brand" label="品牌" width="100" />
                    </el-table>
                </div>
            </div>

            <!-- 分页 -->
            <div style="margin-top: 12px;">
                <el-pagination @size-change="handleGoodsSizeChange" @current-change="handleGoodsCurrentChange"
                    :current-page="goodsPage.current" :page-sizes="[10, 20, 50]" :page-size="goodsPage.size"
                    layout="total, sizes, prev, pager, next, jumper" :total="goodsTotal" />
            </div>

            <!-- 弹窗底部按钮 -->
            <div class="dialog-footer" style="margin-top: 12px">
                <el-button @click="goodsSelectDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmGoodsSelection">选中</el-button>
                <el-button type="primary" @click="confirmAndClose">选中并关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { useRouter } from 'vue-router'; // 引入 useRouter 钩子

export default {
    name: 'TransferOrder',
    setup() {
        const router = useRouter(); // 获取路由实例

        // 处理历史单据跳转
        const handleHistoryBills = () => {
            // 跳转到历史单据列表页面
            router.push({
                name: 'TransferOrderList',
                // 可以传递查询参数或路由参数
                query: {
                    // 例如传递当前日期作为查询条件
                    date: new Date().toISOString().split('T')[0]
                }
            });
        };

        return {
            handleHistoryBills
            // 其他方法...
        };
    },
    data() {
        return {
            form: {
                billDate: '2025-06-25',
                salesman: 'A',
                billNo: 'DB20250625001',
                remark: '',
            },
            salesmanOptions: [
                { label: '业务员A', value: 'A' },
                { label: '业务员B', value: 'B' },
            ],
            warehouseOptions: [
                { label: '主仓库', value: 'main' },
                { label: '分仓库1', value: 'sub1' },
            ],
            tableData: [
                {
                    goodsInput: '',
                    goodsCategory: '',
                    goodsRemark: '',
                    attributeCode: '',
                    brand: '',
                    attribute: '',
                    unit: '',
                    quantity: '',
                    batch: '',
                    wholePackage: '',
                    outWarehouse: '',
                    inWarehouse: '',
                    availableStock: '',
                    relatedOrderNo: '',
                    remark: '',
                },
            ],
            goodsSelectDialogVisible: false,
            currentRow: null,
            currentRowIndex: -1,
            goodsSearchKey: '',
            warehouseFilter: '',
            showZeroStock: false,
            categoryTree: [
                {
                    label: '全部',
                    children: [
                        { label: '茶', children: [{ label: '绿茶' }] },
                        {
                            label: '酒类',
                            children: [
                                {
                                    label: '红酒',
                                    children: [{ label: '国产' }, { label: '进口' }],
                                },
                                { label: '啤酒' },
                            ],
                        },
                        { label: '食品', children: [{ label: '零食' }] },
                        { label: '饮料', children: [{ label: '果汁' }] },
                    ],
                },
            ],
            treeProps: { children: 'children', label: 'label' },
            goodsList: [
                { goodsCode: 'SP0001', goodsName: '巧克力', spec: '100g', brand: '品牌X' },
                { goodsCode: 'SP0002', goodsName: '果味饮料', spec: '500ml', brand: '品牌Y' },
                { goodsCode: 'SP0003', goodsName: '脆饼', spec: '200g', brand: '品牌Z' },
                { goodsCode: 'SP0004', goodsName: '饼干', spec: '150g', brand: '品牌X' },
                { goodsCode: 'SP0005', goodsName: '薯片', spec: '80g', brand: '品牌Y' },
                { goodsCode: 'SP0006', goodsName: '坚果', spec: '120g', brand: '品牌Z' },
                { goodsCode: 'SP0007', goodsName: '糖果', spec: '200g', brand: '品牌X' },
                { goodsCode: 'SP0008', goodsName: '口香糖', spec: '30片', brand: '品牌Y' },
                { goodsCode: 'SP0009', goodsName: '蛋糕', spec: '500g', brand: '品牌Z' },
                { goodsCode: 'SP0010', goodsName: '面包', spec: '300g', brand: '品牌X' },
                { goodsCode: 'SP0011', goodsName: '牛奶', spec: '500ml', brand: '品牌Y' },
                { goodsCode: 'SP0012', goodsName: '酸奶', spec: '200g', brand: '品牌Z' },
                { goodsCode: 'SP0013', goodsName: '咖啡', spec: '100g', brand: '品牌X' },
                { goodsCode: 'SP0014', goodsName: '茶包', spec: '20袋', brand: '品牌Y' },
                { goodsCode: 'SP0015', goodsName: '矿泉水', spec: '500ml', brand: '品牌Z' },
                { goodsCode: 'SP0016', goodsName: '碳酸饮料', spec: '600ml', brand: '品牌X' },
                { goodsCode: 'SP0017', goodsName: '果汁饮料', spec: '500ml', brand: '品牌Y' },
                { goodsCode: 'SP0018', goodsName: '功能性饮料', spec: '330ml', brand: '品牌Z' },
                { goodsCode: 'SP0019', goodsName: '方便面', spec: '100g', brand: '品牌X' },
                { goodsCode: 'SP0020', goodsName: '罐头', spec: '300g', brand: '品牌Y' },
            ],
            goodsPage: { current: 1, size: 10 },
            goodsTotal: 20,
            selectedGoods: [],
            selectedCategories: [],
        };
    },
    methods: {
        handleSalesmanChange(value) {
            console.log('选中业务员:', value);
        },
        handleSaveAndNew() {
            this.$message.success('保存并新增成功（模拟）');
        },
        handleSave() {
            this.$message.success('保存成功（模拟）');
        },
        handleBatchImport() {
            this.$message.info('批量导入功能待实现');
        },
        handleApprove() {
            this.$message.success('审核通过（模拟）');
        },
        handleUploadAttachment() {
            this.$message.info('上传附件功能待实现');
        },
        handleAddRow(index) {
            this.tableData.splice(index + 1, 0, {
                goodsInput: '',
                goodsCategory: '',
                goodsRemark: '',
                attributeCode: '',
                brand: '',
                attribute: '',
                unit: '',
                quantity: '',
                batch: '',
                wholePackage: '',
                outWarehouse: '',
                inWarehouse: '',
                availableStock: '',
                relatedOrderNo: '',
                remark: '',
            });
        },
        handleDeleteRow(index) {
            if (index === 0) {
                this.$message.warning('首行不可删除');
                return;
            }
            this.tableData.splice(index, 1);
        },
        openGoodsSelectDialog(row, index) {
            this.currentRow = row;
            this.currentRowIndex = index;
            this.goodsSelectDialogVisible = true;
        },
        searchGoods() {
            let filtered = this.goodsList.filter((item) => {
                const matchSearch = !this.goodsSearchKey ||
                    item.goodsCode.includes(this.goodsSearchKey) ||
                    item.goodsName.includes(this.goodsSearchKey);
                const matchWarehouse = !this.warehouseFilter || item.warehouse === this.warehouseFilter;
                const matchStock = this.showZeroStock || item.stock > 0;
                return matchSearch && matchWarehouse && matchStock;
            });
            filtered = filtered.filter((item) => {
                return this.selectedCategories.length === 0 ||
                    this.selectedCategories.some(cate => item.category.includes(cate));
            });
            this.goodsList = filtered;
            this.goodsTotal = filtered.length;
        },
        resetGoodsSearch() {
            this.goodsSearchKey = '';
            this.warehouseFilter = '';
            this.showZeroStock = false;
            this.searchGoods();
        },
        handleCategoryCheck(checkedKeys) {
            if (checkedKeys.checkedNodes && checkedKeys.checkedNodes.length > 0) {
                this.selectedCategories = checkedKeys.checkedNodes.map(node => node.label).filter(label => label !== '全部');
            } else {
                this.selectedCategories = [];
            }
            this.searchGoods();
        },
        handleGoodsSelection(selection) {
            this.selectedGoods = selection;
        },
        confirmGoodsSelection() {
            if (this.selectedGoods.length > 0 && this.currentRow) {
                const selected = this.selectedGoods[0];
                // 回填商品信息到当前行
                this.currentRow.goodsInput = selected.goodsName;
                this.currentRow.goodsCategory = selected.spec;
                this.currentRow.brand = selected.brand;
                // 可根据需要添加更多字段回填
            } else {
                this.$message.warning('请选择商品');
            }
        },
        confirmAndClose() {
            this.confirmGoodsSelection();
            this.goodsSelectDialogVisible = false;
        },
        handleGoodsSelectDialogClose() {
            this.currentRow = null;
            this.currentRowIndex = -1;
            this.selectedGoods = [];
            this.goodsSearchKey = '';
            this.warehouseFilter = '';
            this.showZeroStock = false;
            this.selectedCategories = [];
            // 重置商品列表为原始数据
            this.goodsList = [
                { goodsCode: 'SP0001', goodsName: '巧克力', spec: '100g', brand: '品牌X' },
                { goodsCode: 'SP0002', goodsName: '果味饮料', spec: '500ml', brand: '品牌Y' },
                { goodsCode: 'SP0003', goodsName: '脆饼', spec: '200g', brand: '品牌Z' },
                { goodsCode: 'SP0004', goodsName: '饼干', spec: '150g', brand: '品牌X' },
                { goodsCode: 'SP0005', goodsName: '薯片', spec: '80g', brand: '品牌Y' },
                { goodsCode: 'SP0006', goodsName: '坚果', spec: '120g', brand: '品牌Z' },
                { goodsCode: 'SP0007', goodsName: '糖果', spec: '200g', brand: '品牌X' },
                { goodsCode: 'SP0008', goodsName: '口香糖', spec: '30片', brand: '品牌Y' },
                { goodsCode: 'SP0009', goodsName: '蛋糕', spec: '500g', brand: '品牌Z' },
                { goodsCode: 'SP0010', goodsName: '面包', spec: '300g', brand: '品牌X' },
                { goodsCode: 'SP0011', goodsName: '牛奶', spec: '500ml', brand: '品牌Y' },
                { goodsCode: 'SP0012', goodsName: '酸奶', spec: '200g', brand: '品牌Z' },
                { goodsCode: 'SP0013', goodsName: '咖啡', spec: '100g', brand: '品牌X' },
                { goodsCode: 'SP0014', goodsName: '茶包', spec: '20袋', brand: '品牌Y' },
                { goodsCode: 'SP0015', goodsName: '矿泉水', spec: '500ml', brand: '品牌Z' },
                { goodsCode: 'SP0016', goodsName: '碳酸饮料', spec: '600ml', brand: '品牌X' },
                { goodsCode: 'SP0017', goodsName: '果汁饮料', spec: '500ml', brand: '品牌Y' },
                { goodsCode: 'SP0018', goodsName: '功能性饮料', spec: '330ml', brand: '品牌Z' },
                { goodsCode: 'SP0019', goodsName: '方便面', spec: '100g', brand: '品牌X' },
                { goodsCode: 'SP0020', goodsName: '罐头', spec: '300g', brand: '品牌Y' },
            ];
        },
        handleGoodsSizeChange(val) {
            this.goodsPage.size = val;
            this.searchGoods();
        },
        handleGoodsCurrentChange(val) {
            this.goodsPage.current = val;
            this.searchGoods();
        },
        handleCustomFields() {
            this.$message.info('自定义字段功能待实现');
        },
        handleOperationLogs() {
            this.$message.info('查看操作日志功能待实现');
        },
    },
};
</script>

<style scoped>
/* 为整个页面添加固定高度和滚动条 */
.stock-transfer-page {
    padding: 24px;
    background: #fff;
    /* 设置页面高度，超出部分显示滚动条 */
    height: calc(100vh - 48px);
    /* 视口高度减去顶部导航等可能的高度 */
    overflow-y: auto;
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.btn-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.bill-no {
    margin-left: 16px;
    color: #666;
}

.summary-bar {
    margin-top: 8px;
}

.bottom-bar {
    display: flex;
    gap: 8px;
}

/* 商品选择弹窗样式 */
.goods-dialog-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
}

.goods-dialog-body {
    display: flex;
    height: 400px;
}

.category-tree {
    border: 1px solid #ebeef5;
    padding: 8px;
    border-radius: 4px;
    height: 100%;
    overflow-y: auto;
}

.goods-list {
    flex: 1;
    height: 300px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 8px;
}

/* 滚动条样式优化 */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>